package top.jandmla.excel.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import top.jandmla.excel.bean.Role;
import top.jandmla.excel.bean.User;
import top.jandmla.excel.bean.UserRole;
import top.jandmla.excel.dao.RoleMapper;
import top.jandmla.excel.dao.UserMapper;
import top.jandmla.excel.dao.UserRoleMapper;
import top.jandmla.excel.pojo.UserPojo;
import top.jandmla.excel.pojo.UserRolePojo;
import top.jandmla.excel.service.UserRoleService;
import top.jandmla.excel.util.result.BaseResult;

import javax.annotation.Resource;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    /**
     * 修改用户角色
     * @param userRolePojo 用户角色
     * @return 修改结果
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public BaseResult<String> changeRole(UserRolePojo userRolePojo) {
        if (userRolePojo != null){
            UserRole newUserRole = userRolePojo.getNewUserRole();
            UserRole oldUserRole = userRolePojo.getOldUserRole();

            if (!checkUserAndRole(newUserRole) || !checkUserAndRole(oldUserRole))
                return BaseResult.fail(1,"修改失败，请检查用户或角色是否存在！");

            //检查两个用户ID是否一致
            if (!StringUtils.equals(oldUserRole.getUserId(),newUserRole.getUserId()))
                return BaseResult.fail(1,"不可以偷梁换柱！");

            QueryWrapper<UserRole> qwold = checkRoleOfUser(oldUserRole);
            QueryWrapper<UserRole> qwnew = checkRoleOfUser(newUserRole);
            if (qwnew == null)
                if (qwold != null)
                    return userRoleMapper.update(newUserRole,qwold) > 0 ? BaseResult.success("角色改变成功！") : BaseResult.fail(1,"变更失败！");
                else{
                    return userRoleMapper.insert(newUserRole) > 0 ? BaseResult.success("该用户的新旧角色都不存在，已经自动为其添加新角色成功！")
                            : BaseResult.fail(1,"该用户新旧角色都不存在，且自动添加新角色失败，请联系客服！");
                }
            else
                return BaseResult.fail(1,"该用户的新角色已存在！");
        }

        return BaseResult.fail(1,"参数传输不合法！");
    }

    /**
     * 给用户添加新角色
     * @param userRole 用户角色
     * @return 添加结果
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public BaseResult<String> insertUserRole(UserRole userRole){
        if (checkUserAndRole(userRole)){
            QueryWrapper<UserRole> qw = checkRoleOfUser(userRole);
            if (qw == null)
               return userRoleMapper.insert(userRole) > 0 ? BaseResult.success("给用户添加角色成功！")
                       : BaseResult.fail(1,"添加失败，发生未知错误，请联系客服！");
            else
                return BaseResult.fail(1,"添加失败，该用户已经拥有该角色");
        }else
            return BaseResult.fail(1,"参数传输不合法！");
    }

    /**
     * 辞职：检测是否删除自己的角色
     * @param userRole 角色信息
     * @return 删除结果
     */
    @Override
    public BaseResult<String> deleteByUser(UserRole userRole) {
        if (userRole == null)
            return BaseResult.fail(1,"参数传输不合法！");
        UserPojo user = (UserPojo) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.equals(user.getId(),userRole.getUserId()))
            return deleteByUserId(userRole);
        return BaseResult.fail(1,"这里只能删除"+user.getUserName()+"的角色信息！");
    }


    /**
     * 检查用户的某个角色是否存在
     * @param userRole 用户角色信息
     * @return 存在则返回该用户的该角色的QueryWrapper，不存在则返回null
     */
    @Transactional(propagation= Propagation.REQUIRED,readOnly=true,rollbackFor={Exception.class})
    public QueryWrapper<UserRole> checkRoleOfUser(UserRole userRole){
        //判断用户是否存在角色
        QueryWrapper<UserRole> qwur = new QueryWrapper<>();
        qwur.eq("user_id",userRole.getUserId());
        qwur.eq("role_id",userRole.getRoleId());
        if (userRoleMapper.selectCount(qwur) == 0){
            return null;
        }else
            return qwur;
    }




    /**
     * 检车输入用户角色信息是否合法
     * @param userRole 用户角色信息
     * @return 检查结果：true：参数正确，且用户角色都存在；
     *                 false：参数错误，或用户和角色可能不存在。
     */
    @Transactional(propagation= Propagation.REQUIRED,readOnly=true,rollbackFor={Exception.class})
    public boolean checkUserAndRole(UserRole userRole){

        if (userRole == null || StringUtils.isEmpty(userRole.getUserId()) || StringUtils.isEmpty(userRole.getRoleId()))
            return false;
        //判断用户是否存在
        QueryWrapper<User> qwu = new QueryWrapper<>();
        qwu.eq("id",userRole.getUserId());
        if (userMapper.selectCount(qwu) == 0){
            return false;
        }

        //判断角色是否存在
        QueryWrapper<Role> qwr = new QueryWrapper<>();
        qwr.eq("id",userRole.getRoleId());
        return roleMapper.selectCount(qwr) != 0;
    }

    /**
     * 删除用户的角色
     * @param userRole 用户角色
     * @return 删除结果
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public BaseResult<String> deleteByUserId(UserRole userRole) {
        if (userRole != null && !StringUtils.isEmpty(userRole.getUserId())){
            QueryWrapper<UserRole> qw = new QueryWrapper<>();
            qw.eq("user_id",userRole.getUserId());
            qw.eq("role_id",userRole.getRoleId());
            if (userRoleMapper.selectCount(qw) > 0){
                userRoleMapper.deleteByUserId(userRole);
                return BaseResult.success("操作成功！");
            }
            return BaseResult.fail(1,"该用户没有赋予角色！");
        }
        return BaseResult.fail(1,"传输参数不合法！");
    }
}
